<template>
    <div class="page-controller">
      <el-container>
        <el-aside width="240px" class="tree_css">
          <h3>组织机构列表</h3>
          <FITree1
          v-if="isShowTree"
          class="tree_box"
          :treeListObj="treeListObj"
          :filter-node-method="filterNode"
          :showFilter="true"
          :showCheckbox="false"
          @nodeClick="nodeClick"
        ></FITree1>
        </el-aside>
        <el-container>
          <el-main>
            <FISearchForm
              class="box-radius2"
              ref="ruleFormRef"
              :id="`inqu_${tableId}`"
              v-model:form-value="state.query"
              :exclude-values="['subjectId']"
              :table-column="columns"
              :wrapperSpan="searchWrapperSpan"
              @submit="searchFn"
              @reset="state.query.postCname = ''"
            >
              <el-col :span="searchWrapperSpan" class="flex-center">
                <FIFormItem prop="resourceType" label="资源类型">
                  <FISelect
                    v-model="state.query.resourceType"
                    valueCustom="value"
                    :options="[
                      { value: 'PAGE', label: '页面' },
                      { value: 'BUTTON', label: '按钮' },
                    ]"
                    clearable
                  />
                </FIFormItem>
              </el-col>
              <el-col :span="searchWrapperSpan" class="flex-center">
                <FIFormItem name="resourceEname" label="资源编码">
                  <FIInput v-model="state.query.resourceEname" clearable />
                </FIFormItem>
              </el-col>
              <el-col :span="searchWrapperSpan" class="flex-center">
                <FIFormItem prop="resourceCname" label="资源名称">
                  <FIInput v-model="state.query.resourceCname" clearable />
                </FIFormItem>
              </el-col>
            </FISearchForm>
            <div class="margin-bottom20"></div>
            <FITable
              ref="tableRef"
              class="box-radius2"
              title="岗位列表"
              :id="`result_${tableId}`"
              :readonly="false"
              :data="state.dataList"
              primaryKey="groupId"
              v-model:columns="columns"
              :isLoading="isTableLoading"
              :insertable="false"
              deletable
              :showRowNo="true"
              :saveSuccessful="saveSuccessful"
              :pageConfig="pageConfig"
              @row-add-save="addRowSave"
              @table-refresh="searchFn"
              @selection-change="handleSelectionChange"
              @size-change="handleSizeChange"
              @current-page-change="handleCurrentChange"
              @action-click="actionClick"
              @row-delete="deleteRow"
              @on-cell-select="selectClick"
            >
              <template #headerBtn>
                <FIButton id="openMenuTree" border class="margin-left5" @click.stop="btnClick('menu')"></FIButton>
                <FIButton id="openModuleTree" border class="margin-left5" @click.stop="btnClick('model')"></FIButton>

              </template>
            </FITable>
          </el-main>
        </el-container>
      </el-container>
      <FIModel v-model="menuShow" width="700" title="菜单树授权" @close="menuShow = false" @confirm="saveMenuFunc">
        <FIFormItem prop="formEname" label="菜单树列表">
          <menu-list
            @select-node="selectNode"
            style="width: 400px; height: 600px; overflow: auto"
            :buttonPage_Ckeck="true"
          ></menu-list>
        </FIFormItem>
      </FIModel>
      <FIModel v-model="modelShow" width="700" title="模块树授权" @close="modelShow = false" @confirm="saveMenuFunc">
        <el-row :gutter="20">
          <el-col :span="24">
            <FIFormItem prop="formEname" label="模块树列表">
              <model-list
                @select-node="selectNode"
                style="width: 400px; height: 600px; overflow: auto"
                :buttonPage_Ckeck="true"
              ></model-list>
            </FIFormItem>
          </el-col>
        </el-row>
      </FIModel>
    </div>
  </template>
  <script lang="ts" setup>
  import { reactive, onMounted, ref, computed, watch } from 'vue'
  import FISearchForm from '@/components/FISearchForm.vue'
  import FIFormItem from '@/components/FIFormItem.vue'
  import FIInput from '@/components/FIInput.vue'
  import FIButton from '@/components/FIButton.vue'
  import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
  import FITable from '@/components/FITable/index.vue'
  import FICascaderTree from '@/components/FICascaderTree.vue'
  import FIAutoInput from '@/components/FIAutoInput.vue'
  import { apiRequestPost } from '@/api/globalApi.js'
  import LocalCache from '@/utils/cache'
  import menuList from './components/menuList'
  import modelList from './components/modelList'
  import { ElMessage } from 'element-plus'
  import { useMessage } from '@/hooks/message'
  import type { PageConfig, Column } from '@/types/components'
  import { useRoute } from 'vue-router'
  import { initSearchData } from '@/utils/common'
  import { getQueryTableCache } from '@/utils/cacheUtils'
  import {
    apiAuthMaintquery,
    apiAuthMaintdelete,
    apiGetXslvDeptTree,
    apiSaveAuthoritys
  } from '@/api/user'
  import { getCurrentInstance } from 'vue'
  const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
  const route = useRoute()
  
  const searchWrapperSpan = 8
  const menuShow = ref(false)
  const modelShow = ref(false)
  const setShow = ref(false)
  const isTableLoading = ref(false)
  // 页面编码
  const tableId = 'usersManage'
  // 保存成功按钮状态，默认不展示底部保存，取消按钮
  const saveSuccessful = ref(false)
  const tableRef = ref(null)
  const editData = ref({})
  const orgList = ref([])
  const postList = ref([])
  const treeListObj = ref({})
  const treeData = ref([])
  const userlistCurrent = ref(1)
  const loadMoreEnd = ref(false)
  
  const state = reactive({
    query: {
      resourceType: '',
      resourceEname: '',
      resourceCname: '',
      subjectId: '',
      current: '1',
      size: 10,
    },
    dataList: [],
  })
  const pageConfig: PageConfig = reactive({
    total: 0,
    currentPage: 1,
  })
  const columns: Column[] = reactive([
    {
      label: '授权主体编码',
      prop: 'subjectEname',
      align: 'center',
      queryName: '',
      editable: true,
      sortable: false,
      filterable: false,
      required: true,
      readonly: true,
      modelValue: { inputValue: '' },
      editType: 'input',
      // editConfig: {
      //    rules: { groupEname: [{ required: true, message: '请输入用户组编码', trigger: 'blur' }] },
      // },
    },
    {
      label: '授权主体名称',
      prop: 'subjectCname',
      align: 'center',
      queryName: '',
      editable: true,
      sortable: false,
      filterable: false,
  
      modelValue: { inputValue: '' },
      editType: 'input',
    },
    {
      label: '资源编码',
      prop: 'resourceEname',
      align: 'center',
      editable: true,
      editType: 'autoSelect',
      editConfig: {
        otherBinds: {
          apiUrl: '/rm2/deptMaint/query',
          props: { value: 'orgEname', label: 'orgEname' },
          displayKey: ['orgEname', 'orgCname'],
          searchParam: 'orgANameLike',
        },
      },
    },
    {
      label: '资源名称',
      prop: 'resourceCname',
      queryName: '',
      align: 'center',
      editType: 'select',
      editable: false,
      filterable: false,
      sortable: false,
      readonly: true,
      sortValue: '',
      modelValue: { inputValue: '' },
      // editConfig: {
      //   rules: { formCname: [{ required: true, message: '请输入页面名称', trigger: 'blur' }] },
      // },
    },
    {
      label: '创建人',
      prop: 'recCreator',
      align: 'center',
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '创建时间',
      prop: 'recCreateTime',
      align: 'center',
      editType: 'time-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '修改人',
      prop: 'recRevisor',
      align: 'center',
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '修改时间',
      prop: 'recReviseTime',
      align: 'center',
      editType: 'date-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
  ])
  const filterNode = (value: string, data: Tree) => {
    if (!value) return true
    return data.label.includes(value)
  }
  const nodeClick = (val) => {
    state.query.subjectId = val.value
    searchFn('query', '')
  }
  const btnClick = (type) => {
    if (type == 'menu') {
      menuShow.value = true
    }
    if (type == 'model') {
      modelShow.value = true
    }
  }
  const saveMenuFunc = () => {
  let list = treeData.value.map((v) => {
    if (v.payload.resourceId) {
      return {
        resourceId: v.payload.resourceId,
        resourceType: v.payload.resourceType,
      }
    }
  })
  console.log(list, '查看list')
  let par = {
    authorityList: list.filter((item) => item !== undefined),
    subjectId: state.query.subjectId,
    subjectType: 'USER_GROUP'
  }
  apiSaveAuthoritys(par)
    .then((res) => {
      if (res.data.success) {
        useMessage().success(res.data.message)

        menuShow.value = false
        modelShow.value = false
        searchFn('query', '')
      }
    })
    .catch((error: any) => {})
}
  const checkedRows = ref([])
  const handleSelectionChange = (e) => {
    checkedRows.value = e
  }
  const handleSizeChange = (e) => {
    pageConfig.pageSize = e
    pageConfig.currentPage = 1
    searchFn()
  }
  const handleCurrentChange = (e) => {
    pageConfig.currentPage = e
    searchFn('page')
  }
  // const selectClick = (data) => {
  //   console.log(data, 'data123')
  //   state.query.postId = data.postId
  // }
  const selectClick = (scope, item) => {
    console.log(scope, item, '查看')
    if (scope.column.property == 'deptEname') {
      tableRef.value.setCellValue(scope.$index, 'deptCname', item.orgCname)
      tableRef.value.setCellValue(scope.$index, 'orgId', item.orgId)
    }
    if (scope.column.property == 'postEname') {
      tableRef.value.setCellValue(scope.$index, 'postCname', item.postCname)
      tableRef.value.setCellValue(scope.$index, 'postId', item.postId)
    }
  }
  //操作
  const actionClick = (item, rowData, btnInfo) => {
    editData.value = rowData
    if (item.type == 'set') {
      setShow.value = true
    }
  }
  // const selectData = (val,name) =>{
  //   console.log(val,name)
  //   // deptCname
  //   // orgSelect.label = name
  //   // orgSelect.value = val
  // }
  const selectNode = (val) => {
    treeData.value = val
  }
  const searchFn = (type?: string, columnsVal?: any) => {
    const obj = initSearchData(type, columnsVal, columns, state.query)
    isTableLoading.value = true
    state.query = obj.queryData
    columns.values = obj.columns
    if(type == 'page'){
      state.query.current = pageConfig.currentPage
    }else{
      pageConfig.currentPage = 1
      state.query.current = 1
    }
    isTableLoading.value = true
    if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
    const par = {
      ...state.query,
    }
    // const apiUrl = proxy.$Button_api('query', route.name)
    apiAuthMaintquery(par)
      .then((res) => {
        isTableLoading.value = false
        if (res.data.success) {
          state.dataList = res.data.data.result
          pageConfig.pageSize = Number(res.data.data.size)
          pageConfig.total = Number(res.data.data.count)
        } else {
          // ElMessage.error(res.data.message)
        }
      })
      .catch((error: any) => {
        isTableLoading.value = false
        // 处理错误
      })
  }
  const handleSave = () => {
    for (let i of checkedRows.value) {
      if (!i.groupCname) {
        useMessage().warning('请输入用户组名称')
        return
      }
      if (!i.groupEname) {
        useMessage().warning('请输入用户组编码')
        return
      }
    }
    isTableLoading.value = true
    saveSuccessful.value = false
    const apiUrl = proxy.$Button_api('save', route.name)
    apiRequestPost(apiUrl, checkedRows.value)
      .then((res) => {
        isTableLoading.value = false
        if (res.data.success) {
          // saveSuccessful.value = true
          ElMessage.success(res.data.message)
          tableRef.value.clearSelection()
          searchFn()
        } else {
          ElMessage.error(res.data.message)
        }
      })
      .catch((error: any) => {
        isTableLoading.value = false
      })
  }
  const deleteRow = () => {
    if (!checkedRows.value.length) {
      useMessage().warning('请选择一条数据')
      return
    }
    isTableLoading.value = true
    const arr = checkedRows.value.map((v) => {
      return {
        resourceId: v.resourceId,
        resourceType: v.resourceType,
        subjectId: v.subjectId,
        subjectType: v.subjectType,
      }
    })
    apiAuthMaintdelete(arr)
      .then((res) => {
        isTableLoading.value = false
        if (res.data.success) {
          searchFn()
        }
      })
      .catch((error: any) => {
        isTableLoading.value = false
      })
  }
  const ruleFormRef = ref(null)
  
  const addRowSave = (data) => {
    // handleSave()
  }
  const getTreeList = async() => {
      const {data} = await apiGetXslvDeptTree({scene:4})
      if(data.success){
          treeListObj.value = data.data;
          isShowTree.value = true
          console.log(treeListObj.value,'调用了')
      }
    }
    const isShowTree = ref(false)
  onMounted(() => {
    searchFn()
    getTreeList()
    // 获取查询条件缓存
    const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
    if (cachedQuery) state.query = cachedQuery
    if (columns) columns.values = cachedColumns
  })
  </script>
  <style lang="less" scoped>
    .tree_css {
      background: #fff;
      position: relative;
      height: calc(100vh - 200px);
      h3 {
        font-size: 18px;
        line-height: 55px;
        padding-left: 15px;
        border-bottom: 1px solid #eee;
        margin-bottom: 20px;
        color: #000000;
        .icon_css {
          float: right;
          margin-top: 16px;
          margin-right: 12px;
        }
      }
    }
  </style>
  